package com.block.datapush.service.apipush;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.QianHaiMingTouUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

/**
 * 前海明投
 */
@Service
public class QianHaiMingTouApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String secret = pushApiKeyParam.getApiSecret();

        String mobileMd5 = memberSourceInfo.getMobileMd5();

        TreeMap<String, Object> paramMap = new TreeMap<String, Object>();
        long timestamp = System.currentTimeMillis();
        String placeId = RandomUtil.randomNumbers(6);
        paramMap.put("mobile", mobileMd5);
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        String province = memberSourceInfo.getProvince();
        if (StrUtil.endWith(province, "省")) {
            province = memberSourceInfo.getProvince().substring(0, memberSourceInfo.getProvince().length() - 1);
        }
        paramMap.put("location", province + "-" + city);
        paramMap.put("url", "placeId=" + placeId);
        paramMap.put("timestamp", timestamp);
        //TreeMap自动ASCII码排序
        StringBuilder sign = new StringBuilder();
        for (String key : paramMap.keySet()) {
            sign.append(key).append("=").append(paramMap.get(key)).append("&");
        }
        sign.deleteCharAt(sign.length() - 1);
        paramMap.put("sign", SecureUtil.md5(sign+secret).toLowerCase());

        log.info("【前海明投】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【前海明投】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");

        pushApiResult.setCode(code+"");
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            Boolean isExist = data.getBoolean("isExist");
            if (!isExist) {
                pushApiResult.setPushSuccess(true);
            }
            return pushApiResult;
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String secret = pushApiKeyParam.getApiSecret();

        TreeMap<String, Object> paramMap = new TreeMap<String, Object>();
        long time = System.currentTimeMillis();
        String placeId = RandomUtil.randomNumbers(6);
        String cusTypeStr = QianHaiMingTouUtil.getCusTypeStr(memberSourceInfo.getHouse(), memberSourceInfo.getCar());
        paramMap.put("cusTypeStr", cusTypeStr);
//        paramMap.put("cusSourceNum", RandomUtil.randomNumbers(3)+"num");
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        String province = memberSourceInfo.getProvince();
        if (StrUtil.endWith(province, "省")) {
            province = memberSourceInfo.getProvince().substring(0, memberSourceInfo.getProvince().length() - 1);
        }
        paramMap.put("customerLocation", province + "-" + city);
        paramMap.put("mobile", memberSourceInfo.getMobile());
        paramMap.put("remark", QianHaiMingTouUtil.getRemark(memberSourceInfo.getZhima(),memberSourceInfo.getGjj(),memberSourceInfo.getShebao()));
        paramMap.put("clueId", UUID.randomUUID().toString());
        paramMap.put("loanAmount", QianHaiMingTouUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("createTime", time);
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("cusSourceType", "臻享分期");
        paramMap.put("timestamp", time);
        paramMap.put("ip", QianHaiMingTouUtil.getReqIp(memberSourceInfo.getReqIp()));
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("sex",QianHaiMingTouUtil.getSex(memberSourceInfo.getSex()));
        paramMap.put("url", "placeId=" + placeId);
        //TreeMap自动ASCII码排序
        StringBuilder sign = new StringBuilder();
        for (String key : paramMap.keySet()) {
            sign.append(key).append("=").append(paramMap.get(key)).append("&");
        }
        sign.deleteCharAt(sign.length() - 1);
        paramMap.put("sign", SecureUtil.md5(sign+secret).toLowerCase());

        log.info("【前海明投】导单开始【requestUrl】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【前海明投】导单结束【result】{}", result);


        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");
        String data = resultObject.getString("data");


        pushApiResult.setCode(code+"");
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200") && StrUtil.equals(String.valueOf(data), "success")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

}
